<template>
  <div>
    <div
      :id="id"
      :class="className"
      :style="boxStyles"
    />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import { MOCKDATA } from './mock/mapdata'
// import AMapLoader from '@amap/amap-jsapi-loader'
// import china from './mock/china_area.json'
// echarts.registerMap('china', china)
// import china from '@/assets/map/js/china.js'
// import chinaSvg from './mock/china.svg'
// const chinaSvg = require('./mock/china.svg')
// import china from './mock/china.json'
import china from './mock/china.json'
echarts.registerMap('china', china)

export default {
  name: 'MapChart',
  mixins: [resize],
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    xLabels: {
      type: Array,
      default: () => {
        return []
      }
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '800px'
    },
    backgroundColor: {
      type: String,
      default: 'transparent'
    }
  },
  data() {
    return {
      chart: null,
      tempOptions: null,

      chartItemSerie: {
        name: '--',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 5,
        showSymbol: false,
        lineStyle: {
          normal: {
            width: 1
          }
        },
        itemStyle: {
          normal: {
            color: 'rgb(137, 189, 27)',
            borderColor: 'rgba(137, 189, 2, 0.27)',
            borderWidth: 8
          }
        },
        data: []
      },
      data2: [
        {
          name: '下单量',
          color: 'primary',
          data: [
            {
              date: '2',
              value: 1220
            },
            {
              date: '',
              value: 2182
            },
            {
              date: '',
              value: 3191
            },
            {
              date: '',
              value: 1134
            },
            {
              date: '',
              value: 2150
            },
            {
              date: '',
              value: 3120
            },
            {
              date: '',
              value: 2110
            },
            {
              date: '',
              value: 125
            },
            {
              date: '',
              value: 145
            },
            {
              date: '',
              value: 4122
            },
            {
              date: '',
              value: 7165
            },
            {
              date: '',
              value: 822
            }
          ]
        },
        {
          name: '成交量',
          color: 'success',
          items: []
        },
        {
          name: '退款量',
          color: 'warning',
          items: []
        }
      ],
      map: null
    }
  },
  computed: {
    boxStyles() {
      return { height: this.height, width: this.width }
    },
    categorys() {
      if (this.data && this.data.length) {
        return this.data.map(item => {
          return item.name
        })
      }
      return []
    },
    series() {
      var defaultSerie = this.chartItemSerie
      if (this.data && this.data.length) {
        return this.data.map(item => {
          return { ...defaultSerie, ...item }
        })
      }
      return []
    },
    interval() {
      var lens = this.xLabels.length
      return Math.ceil(lens / 6)
    }
  },
  watch: {
    data() {
      this.initChart()
    }
  },
  beforeMount() {
    // https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json
    // AMapLoader.load({
    //   key: 'c573541ee962147adc05c894114ba8ea', // 刚刚开发者申请哪里的key
    //   plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType']
    // })
    //   .then(AMap => {
    //     this.map = new AMap.Map('container')
    //   })
    //   .catch(e => {
    //     console.log(e)
    //   })
  },
  mounted() {
    // 配置option
    // const url = 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json'
    // this.axios.get(url).then(res => {
    //   console.log(res.data)
    //   echarts.registerMap('china', res.data)
    //   this.initChart()
    // })
    // var svgMap = this.readFile('./mock/china.svg')
    // echarts.registerMap('china', { svg: this.chinaSvg })
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    /**
     * 读取svg文件
     * @filePath:svg文件路径
     */
    readFile: filePath => {
      // 创建一个新的xhr对象
      let xhr = null
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
      } else {
        // eslint-disable-next-line no-undef
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
      }
      const okStatus = document.location.protocol === 'file' ? 0 : 200
      xhr.open('GET', filePath, false)
      xhr.overrideMimeType('image/svg+xml')
      xhr.send(null)
      return xhr.status === okStatus ? xhr.responseText : null
    },
    readJson() {
      const url = 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json'
      this.axios.get(url).then(res => {
        console.log(res.data)
        echarts.registerMap('china', res.data)
      })
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      this.chart = echarts.init(document.getElementById(this.id))

      var option

      const data = MOCKDATA.data
      const geoCoordMap = MOCKDATA.geoCoordMap
      const convertData = function(data) {
        var res = []
        for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name]
          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value)
            })
          }
        }
        return res
      }
      option = {
        title: {
          text: '全国主要城市空气质量 - 百度地图',
          subtext: 'data from PM25.in',
          sublink: 'http://www.pm25.in',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        geo: {
          map: 'china',
          label: {},
          // roam: true,
          center: [104.114129, 37.550339],
          roam: false,
          // zoom: 1.5,
          itemStyle: {
            areaColor: 'transparent',
            itemStyle: {
              borderWidth: 4,
              borderType: 'solid'
              // borderType: [5, 10],
              // borderDashOffset: 5
            }
          },
          regions: [
            {
              name: '南海诸岛',
              itemStyle: {
                opacity: 0,
                label: {
                  show: false
                }
              }
            }
          ]
          // regions: makeTakenRegions(china)
        },
        series: [
          {
            type: 'map',
            map: 'china',
            center: [104.114129, 37.550339],
            // zoom: 1.5,
            itemStyle: {
              // areaColor: '#0d0059',
              areaColor: 'transparent',
              borderColor: '#389dff',
              borderWidth: 0.5,
              borderType: 'dashed',
              // borderType: [5, 10],
              borderDashOffset: 5
            },
            regions: [
              {
                name: '南海诸岛',
                itemStyle: {
                  opacity: 0,
                  label: {
                    show: false
                  }
                }
              }
            ]
            // emphasis: {
            //   color: 'green',
            //   areaColor: '#17008d',
            //   borderWidth: 0
            // }
          },
          {
            name: 'pm2.5',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: convertData(data),
            symbolSize: function(val) {
              return val[2] / 10
            },
            encode: {
              value: 2
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: false
            },
            emphasis: {
              label: {
                show: true
              }
            }
          },
          {
            name: 'Top 5',
            type: 'effectScatter',
            coordinateSystem: 'bmap',
            data: convertData(
              data
                .sort(function(a, b) {
                  return b.value - a.value
                })
                .slice(0, 6)
            ),
            symbolSize: function(val) {
              return val[2] / 10
            },
            encode: {
              value: 2
            },
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke'
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: true
            },
            itemStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            },
            emphasis: {
              scale: true
            },
            zlevel: 1
          }
        ]
      }
      option && this.chart.setOption(option)

      // var amapComponent = this.chart.getModel().getComponent('amap')
      // console.log('amapComponent', amapComponent)
      // // get the instance of AMap
      // var amap = amapComponent.getAMap()
      // console.log(amap)
      // operations below are the same as amap
      // amap.addControl(new this.$AMap.Scale())
      // amap.addControl(new this.$AMap.ToolBar())
    }
  }
}
</script>
